package com.chineseall.rebirth.bridge.service;

import jmind.core.redis.SingleJedis;
import jmind.core.util.DataUtil;
import jmind.resource.zk.ZKProperties;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

import com.alibaba.fastjson.JSON;
import com.chineseall.rebirth.api.helper.Const;
import com.chineseall.rebirth.api.pojo.BusEvent;
import com.chineseall.rebirth.api.service.Callback;
import com.chineseall.rebirth.api.service.IBusService;

public class RedisBusService implements IBusService {

    private final SingleJedis jedis;

    public RedisBusService() {
        final String hosts = ZKProperties.getInstance().getProperty("redis.bus.host");
        // 超时时间，单位秒，默认20
        int timeout = DataUtil.toInt(ZKProperties.getInstance().getProperty("redis.bus.timeout", "30"));
        jedis = new SingleJedis(hosts, timeout);

    }

    @Override
    public void addEvent(BusEvent event) {

    }

    @Override
    public void notify(BusEvent event) {
        Jedis resource = jedis.getResource();
        try {
            resource.publish(Const.IBUS_EVENT + event.getTopic(), event.toString());
        } catch (Exception e) {
        } finally {
            jedis.close(resource);
        }
    }

    @Override
    public void subscribe(final String topic, final boolean all, final Callback callback) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                jedis.getResource().subscribe(new JedisPubSub() {

                    @Override
                    public void onUnsubscribe(String channel, int subscribedChannels) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onSubscribe(String channel, int subscribedChannels) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPUnsubscribe(String pattern, int subscribedChannels) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPSubscribe(String pattern, int subscribedChannels) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPMessage(String pattern, String channel, String message) {

                    }

                    @Override
                    public void onMessage(String channel, String message) {
                        try {
                            BusEvent event = JSON.parseObject(message, BusEvent.class);
                            callback.doIt(event);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, Const.IBUS_EVENT + topic);

            }
        }).start();

    }
}
